using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataService.Helper;
using DataService.Helper.Kafka;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Opc.Ua.Sample.Service;
using OpcuaClient.Model;
using OpcuaClient.Service;
using OpcuaClient.View;

namespace OpcuaClient
{
    public partial class MainForm : Form
    {
        LogHelper LogHelper = new LogHelper("OpcuaClient");
        CollectServer Server { get; set; }
        /// <summary>
        /// 服务器业务逻辑
        /// </summary>
        List<OpcConnectService> ServerServiceList { get; set; }
        public MainForm()
        {
            InitializeComponent();

            splitContainer1.SplitterDistance = 260;
            splitContainer2.SplitterDistance = 260;
            splitContainer3.SplitterDistance = 360;
            splitContainer4.SplitterDistance = 400;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            ServerServiceList = new List<OpcConnectService>();
            if (AppService.App.CollectServers.Count > 0)
            {
                //加载配置好的OPC服务
                LoadServer();
            }
            else
            {
                AddServer();
            }
        }

        #region 初始化OPC 服务

        /// <summary>
        /// 切换当前OPC client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btServer1_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            Server = AppService.App.CollectServers.FirstOrDefault(m => m.Name == button.Text);
            ClearUrrentServer();
            //如果服务不存在，删除服务
            if (Server == null || string.IsNullOrWhiteSpace(button.Text))
            {
                if (AddServer())
                {
                    button.Text = Server.Code;
                }
            }
            else
            {
                InitServer(Server);
            }

            ListenerCollectionStatus();
        }

        private void btRestartServer_Click(object sender, EventArgs e)
        {
            ReConnectServer();
        }
        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btStopServer_Click(object sender, EventArgs e)
        {
            if (Server == null) return;
            var service = ServerServiceList.FirstOrDefault(m => m.Server.Code == Server.Code);
            if (service == null) return;
            service.Stop();
            ListenerCollectionStatus();

            lvAttributes.Items.Clear();
            StopRefreshCollection();
        }

        /// <summary>
        /// 重新连接服务器
        /// </summary>
        private void ReConnectServer()
        {
            if (Server == null || string.IsNullOrWhiteSpace(Server.Url)) return;
            var serverService = ServerServiceList.FirstOrDefault(m => m.Server.Code == Server.Code);
            if (serverService == null)
            {
                serverService = new OpcConnectService(Server);
                if (serverService != null)
                {
                    ServerServiceList.Add(serverService);
                }
            }
            else
            {
                int idx = ServerServiceList.IndexOf(serverService);
                serverService.Stop();
                serverService = new OpcConnectService(Server);
                ServerServiceList[idx] = serverService;
            }
            serverService.ConnectStatusEvent += new EventHandler(UpdateServerStatus);
            serverService.ConnectEvent += new EventHandler(StartCollection);
            serverService.StartServer();
            ListenerCollectionStatus();
        }
        /// <summary>
        /// 更新服务器状态
        /// </summary>
        /// <param name="buttonName"></param>
        /// <param name="serverName"></param>
        private void UpdateButton(string buttonName, string serverName)
        {
            switch (buttonName)
            {
                case "Server1": btServer1.Text = serverName; break;
                case "Server2": btServer2.Text = serverName; break;
                case "Server3": btServer3.Text = serverName; break;
                case "Server4": btServer4.Text = serverName; break;
                case "Server5": btServer5.Text = serverName; break;
                case "Server6": btServer6.Text = serverName; break;
                case "Server7": btServer7.Text = serverName; break;
                case "Server8": btServer8.Text = serverName; break;
                case "Server9": btServer9.Text = serverName; break;
                case "Server10": btServer10.Text = serverName; break;
                case "Server11": btServer11.Text = serverName; break;
                case "Server12": btServer12.Text = serverName; break;
            }
        }
        /// <summary>
        /// 当程序启动时加载所有OPC CLIENT
        /// </summary>
        private void LoadServer()
        {
            if (AppService.App.CollectServers == null || AppService.App.CollectServers.Count == 0) return;

            Server = AppService.App.CollectServers[0];
            InitServer(Server);

            for (int i = 0; i < AppService.App.CollectServers.Count; i++)
            {
                ConnectServer(AppService.App.CollectServers[i], i);
            }

            if (ServerServiceList.Count > 0)
            {
                foreach (var item in ServerServiceList)
                {
                    item.StartServer();
                }
                ListenerCollectionStatus();
            }
        }

        /// <summary>
        /// 初始化服务列表，标注服务名称
        /// </summary>
        /// <param name="server"></param>
        /// <param name="i"></param>
        private void ConnectServer(CollectServer server, int idx)
        {
            //当前服务信息无效时不加载
            if (server == null) return;
            switch (idx)
            {
                case 0: btServer1.Text = server.Name; btServer1.BackColor = Color.DarkRed; break;
                case 1: btServer2.Text = server.Name; btServer2.BackColor = Color.DarkRed; break;
                case 2: btServer3.Text = server.Name; btServer3.BackColor = Color.DarkRed; break;
                case 3: btServer4.Text = server.Name; btServer4.BackColor = Color.DarkRed; break;
                case 4: btServer5.Text = server.Name; btServer5.BackColor = Color.DarkRed; break;
                case 5: btServer6.Text = server.Name; btServer6.BackColor = Color.DarkRed; break;
                case 6: btServer7.Text = server.Name; btServer7.BackColor = Color.DarkRed; break;
                case 7: btServer8.Text = server.Name; btServer8.BackColor = Color.DarkRed; break;
                case 8: btServer9.Text = server.Name; btServer9.BackColor = Color.DarkRed; break;
                case 9: btServer10.Text = server.Name; btServer10.BackColor = Color.DarkRed; break;
                case 10: btServer11.Text = server.Name; btServer11.BackColor = Color.DarkRed; break;
                case 11: btServer12.Text = server.Name; btServer12.BackColor = Color.DarkRed; break;
            }
            if (string.IsNullOrWhiteSpace(server.Url)) return;

            OpcConnectService connectService = new OpcConnectService(server);
            connectService.ConnectStatusEvent += new EventHandler(UpdateServerStatus);
            connectService.ConnectEvent += new EventHandler(StartCollection);
            ServerServiceList.Add(connectService);
        }
        #endregion

        #region 配置OPC Client

        /// <summary>
        /// 配置服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btServerConfig_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(lbCode.Text) || lbCode.Text == "Code")
            {
                AddServer();
            }
            else
            {
                ConfigServer();
            }
            if (Server != null)
            {
                UpdateButton(lbCode.Text, Server?.Name);
            }
        }

        /// <summary>
        /// 保存数据采集服务器配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSave_Click(object sender, EventArgs e)
        {
            AppService.SaveServer();
        }
        /// <summary>
        /// 添加服务器
        /// </summary>
        private bool AddServer()
        {
            Form_CollectionServerConfig serverConfig = new Form_CollectionServerConfig();
            serverConfig.ShowDialog(this);
            if (!serverConfig.Status) return false;
            Server = serverConfig.Server;
            //AppService.App.CollectServers.Add(serverConfig.Server);
            UpdateServer(serverConfig.Server);

            OpcConnectService connectService = new OpcConnectService(serverConfig.Server);
            connectService.ConnectStatusEvent += new EventHandler(UpdateServerStatus);
            connectService.ConnectEvent += new EventHandler(StartCollection);
            connectService.ListenerServerStatus();

            ServerServiceList.Add(connectService);
            return true;
        }
        /// <summary>
        /// 保存服务器更新
        /// </summary>
        /// <param name="server"></param>
        private void UpdateServer(CollectServer server)
        {
            var server2 = AppService.App.CollectServers.FirstOrDefault(m => m.Code == server.Code);
            if (server2 == null)
            {
                MessageBox.Show(this, "更新失败！", "错误提示！");
            }
            int idx = AppService.App.CollectServers.IndexOf(server2);
            AppService.App.CollectServers[idx] = server;
        }

        /// <summary>
        /// 修改服务器
        /// </summary>
        private void ConfigServer()
        {
            Form_CollectionServerConfig serverConfig = new Form_CollectionServerConfig();
            int idx = AppService.App.CollectServers.IndexOf(Server);
            serverConfig.Server = Server;
            serverConfig.Config();
            serverConfig.ShowDialog(this);

            Server = serverConfig.Server;
            AppService.App.CollectServers[idx] = Server;

            InitServer(Server);

            ListenerCollectionStatus();
        }
        /// <summary>
        /// 配置服务器展示
        /// </summary>
        /// <param name="server"></param>
        private void InitServer(CollectServer server)
        {
            if (server == null) return;
            lbCode.Text = server.Code;
            lbName.Text = server.Name;
            lbUrl.Text = server.Url;
            lbMessageType.Text = server.MessageType;
            lbMessageUrl.Text = server.MessageUrl;
            lbFrequency.Text = server.Frequency.ToString();
            lbTime.Text = "";
            //加载当前服务器结构体
            LoadConstruction();
            //加载当前服务器采集结点
            LoadColletion();
        }
        /// <summary>
        /// 清空当前服务器信息
        /// </summary>
        private void ClearUrrentServer()
        {
            lbCode.Text = "";
            lbName.Text = "";
            lbUrl.Text = "";
            lbMessageType.Text = "";
            lbMessageUrl.Text = "";
            lbFrequency.Text = "";
            lbTime.Text = "";
            lvConstruction.Items.Clear();
            lvCollection.Items.Clear();
        }
        /// <summary>
        /// 当Session创建后开始数据采集
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        public void StartCollection(object obj, EventArgs e)
        {
            var service = ServerServiceList.FirstOrDefault(m => m.Server.Code == obj.ToString());
            service.StartCollect();
            service.StartConstruction();
            service.StartWriter();
        }
        /// <summary>
        /// 修改服务器连接状态
        /// </summary>
        /// <param name="status"></param>
        public void UpdateServerStatus(object obj, EventArgs e)
        {
            if (obj == null) return;
            CollectServer server = (CollectServer)obj;
            this.btServer1.Invoke(new MethodInvoker(delegate {
                switch (server.Code)
                {
                    case "Server1": btServer1.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server2": btServer2.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server3": btServer3.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server4": btServer4.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server5": btServer5.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server6": btServer6.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server7": btServer7.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server8": btServer8.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server9": btServer9.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server10": btServer10.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server11": btServer11.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                    case "Server12": btServer12.BackColor = bool.Parse(server.Status) ? Color.Green : Color.DarkRed; break;
                }

                if (!bool.Parse(server.Status))
                {
                    KafkaProducer Producer = new KafkaProducer();
                    Producer.Produce(Server.MessageUrl, "OPC_RUN_STATUS", JsonConvert.SerializeObject(new { Server = server.Name, Address = server.Url, Status = server.Status, CreatedTime = DateTime.Now }));
                }
            }));
        }
        #endregion

        #region 配置结构体

        /// <summary>
        /// 添加结构体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btConstructionConfig_Click(object sender, EventArgs e)
        {
            AddConstruction();
        }

        /// <summary>
        /// 添加结构体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加结构体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddConstruction();
        }

        private void 配置结构体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lvConstruction.SelectedItems;
            if (items.Count == 0) return;
            var construction = (Construction)items[0].Tag;
            ConfigConstruction(construction);
        }
        private void 删除结构体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lvConstruction.SelectedItems;
            if (items.Count == 0) return;
            var construction = (Construction)items[0].Tag;
            DeleteConstruction(construction.Key);
        }

        private void 配置结构体参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lvConstruction.SelectedItems;
            if (items.Count == 0) return;
            Construction construction = (Construction)items[0].Tag;
            Form_Construction formConstruction = new Form_Construction();
            formConstruction.Config(construction);
            formConstruction.ShowDialog(this);
            if (formConstruction.Status)
            {
                AddConstructionToServer(formConstruction.Construction);
            }
        }

        /// <summary>
        /// 添加结构体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddConstruction()
        {
            if (Server == null || Server.Code != lbCode.Text)
            {
                Server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == lbCode.Text);
                if (Server == null)
                {
                    MessageBox.Show(this, "请先选择要操作的服务器", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            Form_Construction formConstruction = new Form_Construction();

            //if (!string.IsNullOrWhiteSpace(lbConstrutions.Text))
            //{
            //    Construction construction = Server.Constructions.FirstOrDefault(m => m.Key == lbConstrutions.Text);
            //    formConstruction.Config(construction);
            //}

            formConstruction.ShowDialog(this);
            if (formConstruction.Status)
            {
                AddConstructionToServer(formConstruction.Construction);
            }
        }
        /// <summary>
        /// 配置结构体
        /// </summary>
        /// <param name="key"></param>
        private void ConfigConstruction(Construction construction)
        {
            if (construction == null || Server == null || Server.Code != lbCode.Text)
            {
                Server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == lbCode.Text);
                if (Server == null)
                {
                    MessageBox.Show(this, "请先选择要操作的服务器", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            Form_ConstructionConfig formConstruction = new Form_ConstructionConfig(construction);
            formConstruction.Construction = construction;
            var serverService = ServerServiceList.FirstOrDefault(m => m.SessionName == Server.Code);
            if (serverService != null)
            {
                if (construction.KeyValues == null)
                {
                    construction.KeyValues = new List<ConstructionKeyValue>();
                }
                formConstruction.InitNodeSource(serverService, Server.Collections);
                formConstruction.ShowDialog(this);
                if (formConstruction.Status)
                {
                    AddConstructionToServer(formConstruction.Construction);
                }
            }
        }
        /// <summary>
        /// 删除结构体
        /// </summary>
        /// <param name="key"></param>
        private void DeleteConstruction(string key)
        {
            if (Server == null || Server.Code != lbCode.Text)
            {
                Server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == lbCode.Text);
                if (Server == null)
                {
                    MessageBox.Show(this, "请先选择要操作的服务器", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            Construction construction = Server.Constructions.FirstOrDefault(m => m.Key == key);
            Server.Constructions.Remove(construction);
            LoadConstruction();
        }
        /// <summary>
        /// 添加结构体到服务器
        /// </summary>
        /// <param name="construction"></param>
        /// <param name="idx"></param>
        private void AddConstructionToServer(Construction construction, int idx = -1)
        {
            if (idx == -1)
            {
                Construction construction2 = Server.Constructions.FirstOrDefault(m => m.Key == construction.Key);
                if (construction2 != null)
                {
                    idx = Server.Constructions.IndexOf(construction2);
                }
            }
            if (idx > -1)
            {
                Server.Constructions[idx] = construction;
            }
            else
            {
                Server.Constructions.Add(construction);
            }
            var server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == Server.Code);
            if (server != null)
            {
                int serverIdx = AppService.App.CollectServers.IndexOf(server);
                AppService.App.CollectServers[serverIdx] = Server;
                LoadConstruction();
            }
            else
            {
                var result = MessageBox.Show(this, "服务器不存在，是否添加！", "错误提示！", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                if (result == DialogResult.Cancel)
                {
                    return;
                }
                if (AppService.App.CollectServers.Count >= 12)
                {
                    MessageBox.Show(this, "服务器数量已达12台，不能添加！", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                AppService.App.CollectServers.Add(server);
                LoadServer();
            }
        }

        /// <summary>
        /// 加载结构体
        /// </summary>
        private void LoadConstruction()
        {
            lvConstruction.Items.Clear();
            lvConstruction.BeginUpdate();
            foreach (var construction in Server.Constructions)
            {
                ListViewItem item = new ListViewItem();
                item.ImageIndex = lvConstruction.Items.Count;
                item.Text = construction.Name;
                item.SubItems.Add(construction.Frequency.ToString());
                item.SubItems.Add(construction.Topic);
                item.Tag = construction;
                lvConstruction.Items.Add(item);
            }
            lvConstruction.EndUpdate();
            lvConstruction.Refresh();

            lvAttributes.Items.Clear();
            ///重启点位刷新
            RestartRefreshCollection();
        }
        #endregion

        #region 配置数据采集点位
        /// <summary>
        /// 配置服务器点位信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCollectionConfig_Click(object sender, EventArgs e)
        {
            AddConfigCollection();
        }

        private void 添加点位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddCollection();
        }

        private void 配置采集点位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lvCollection.SelectedItems;
            if (items.Count == 0) return;
            Collection collection = (Collection)items[0].Tag;
            ConfigCollection(collection);
        }

        private void 删除点位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lvCollection.SelectedItems;
            if (items.Count == 0) return;
            for (int i = 0; i < items.Count; i++)
            {
                Collection collection = (Collection)items[i].Tag;
                DeleteCollection(collection);
                lvCollection.Items.Remove(items[i]);
            }
            LoadColletion();
        }

        /// <summary>
        /// 添加采集点位
        /// </summary>
        private void AddCollection()
        {
            if (Server == null || Server.Code != lbCode.Text)
            {
                Server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == lbCode.Text);
                if (Server == null)
                {
                    MessageBox.Show(this, "请先选择要操作的服务器", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            AddConfigCollection();
        }
        private void AddConfigCollection()
        {
            OpcConnectService connectService = ServerServiceList.FirstOrDefault(m => m.SessionName == Server.Code);
            if (connectService == null)
            {
                MessageBox.Show(this, "系统未获取到Session", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (connectService.Session == null || !connectService.Session.Connected)
            {
                MessageBox.Show(this, "Session连接异常", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Form_CollectionConfig collectionConfig = new Form_CollectionConfig(connectService);
            collectionConfig.ShowDialog(this);
            if (collectionConfig.Status)
            {
                //添加配置的点位到服务器
                AddCollectionToServer(collectionConfig.Collections);
            }
        }

        /// <summary>
        /// 配置采集点位
        /// </summary>
        private void ConfigCollection(Collection collection)
        {
            if (Server == null || Server.Code != lbCode.Text)
            {
                Server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == lbCode.Text);
                if (Server == null)
                {
                    MessageBox.Show(this, "请先选择要操作的服务器", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            if (collection == null) return;

            Form_Collection formCollection = new Form_Collection();
            formCollection.Config(collection);
            formCollection.ShowDialog(this);

            if (formCollection.Status)
            {
                Collection collection2 = Server.Collections.FirstOrDefault(m => m.Key == collection.Key);
                int idx = Server.Collections.IndexOf(collection2);
                AddCollectionToServer(formCollection.Collection, idx);
            }
        }

        private void DeleteCollection(Collection collection)
        {
            if (Server == null || Server.Code != lbCode.Text)
            {
                Server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == lbCode.Text);
                if (Server == null)
                {
                    MessageBox.Show(this, "请先选择要操作的服务器", "错误提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            if (collection == null) return;

            Collection collection2 = Server.Collections.FirstOrDefault(m => m.Key == collection.Key);
            Server.Collections.Remove(collection2);
        }

        /// <summary>
        /// 添加点位到服务器
        /// </summary>
        /// <param name="collections"></param>
        private void AddCollectionToServer(List<Collection> collections)
        {
            int idx = 0;
            foreach (var item in collections)
            {
                var collection = Server.Collections.FirstOrDefault(m => m.Key == item.Key);
                if (collection != null)
                {
                    idx = Server.Collections.IndexOf(collection);
                    var result = MessageBox.Show(this, $"<{item.Key}>点位已存在是否替换", "异常提醒！", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                    if (result == DialogResult.Cancel) continue;
                    Server.Collections[idx] = item;
                }
                else
                {
                    Server.Collections.Add(item);
                }
            }
            var server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == Server.Code);
            if (server != null)
            {
                idx = AppService.App.CollectServers.IndexOf(server);
                AppService.App.CollectServers[idx] = server;
                Server = server;
                InitServer(server);
                LoadColletion();
            }
        }

        /// <summary>
        /// 添加点位到服务器
        /// </summary>
        /// <param name="collections"></param>
        private void AddCollectionToServer(Collection collection, int idx = -1)
        {
            if (idx == -1)
            {
                Server.Collections.Add(collection);
            }
            else
            {
                Server.Collections[idx] = collection;
            }

            var server = AppService.App.CollectServers.FirstOrDefault(m => m.Code == Server.Code);
            if (server != null)
            {
                idx = AppService.App.CollectServers.IndexOf(server);
                AppService.App.CollectServers[idx] = server;
                Server = server;
                InitServer(server);
                LoadColletion();
            }
        }
        /// <summary>
        /// 加载采集点位
        /// </summary>
        private void LoadColletion()
        {
            lvCollection.Items.Clear();
            lvCollection.BeginUpdate();
            foreach (var collection in Server.Collections)
            {
                ListViewItem item = new ListViewItem();
                item.ImageIndex = lvCollection.Items.Count;
                item.Text = collection.Name;
                item.SubItems.Add(collection.Frequency.ToString());
                item.SubItems.Add(collection.Address);
                item.Tag = collection;
                lvCollection.Items.Add(item);
            }
            lvCollection.EndUpdate();
            lvCollection.Refresh();
        }
        #endregion
        /// <summary>
        /// 关闭窗口前先关闭数据采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭所有服务器连接
            Task.Factory.StartNew(() => {
                foreach (var item in ServerServiceList)
                {
                    item.Stop();
                }
            });
            ///停止点位刷新
            StopRefreshCollection();
            //停止服务器状态监听
            if (ListenerCollectionStatusThread != null/* && ListenerCollectionStatusThread.IsAlive*/) { ListenerCollectionStatusThread.Abort(); }

            var result = MessageBox.Show(this, $"是否保存当前程序变动", "提醒！", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            if (result == DialogResult.Yes)
            {
                AppService.SaveServer();
            }
        }

        private void lvCollection_DoubleClick(object sender, EventArgs e)
        {
            var items = lvCollection.SelectedItems;
            if (items.Count == 0) return;
            Collection collection = (Collection)items[0].Tag;

            lvAttributes.BeginUpdate();

            ListViewItem item = new ListViewItem();
            item.ImageIndex = lvAttributes.Items.Count;
            item.Text = collection.Name;
            item.SubItems.Add(collection.Address);
            item.SubItems.Add(collection.Value.ToString());
            item.SubItems.Add(collection.DataType);
            item.SubItems.Add(collection.CollectTime.ToString("HH:mm:ss"));
            item.Tag = collection;
            lvAttributes.Items.Add(item);

            lvAttributes.EndUpdate();
            lvAttributes.Refresh();

            ///重启点位刷新
            RestartRefreshCollection();
        }

        private void lvConstruction_DoubleClick(object sender, EventArgs e)
        {
            var items = lvConstruction.SelectedItems;
            if (items.Count == 0) return;
            Construction construction = (Construction)items[0].Tag;

            lvAttributes.BeginUpdate();
            foreach (var keyValue in construction.KeyValues)
            {
                ListViewItem item = new ListViewItem();
                Collection collection = Server.Collections.FirstOrDefault(m => m.Key == keyValue.Key);
                item.ImageIndex = lvAttributes.Items.Count;
                item.Text = collection.Name;
                item.SubItems.Add(collection.Address);
                item.SubItems.Add(collection.Value.ToString());
                item.SubItems.Add(collection.DataType);
                item.SubItems.Add(collection.CollectTime.ToString("HH:mm:ss"));
                item.Tag = collection;
                lvAttributes.Items.Add(item);
            }
            lvAttributes.EndUpdate();
            lvAttributes.Refresh();

            ///重启点位刷新
            RestartRefreshCollection();
        }

        private void 删除当前选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lvAttributes.SelectedItems;
            if (items.Count == 0) return;
            for (int i = 0; i < items.Count; i++)
            {
                lvAttributes.Items.Remove(items[i]);
            }
            ///重启点位刷新
            RestartRefreshCollection();
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StopRefreshCollection();
            lvAttributes.Items.Clear();
        }


        Thread ListenerCollectionStatusThread;
        /// <summary>
        /// 监听服务器当前点位采集状态
        /// </summary>
        private void ListenerCollectionStatus()
        {
            if (ServerServiceList == null || ServerServiceList.Count == 0) return;
            if (ListenerCollectionStatusThread != null /*&& ListenerCollectionStatusThread.IsAlive*/) { ListenerCollectionStatusThread.Abort(); }
            ListenerCollectionStatusThread = new Thread(() => {
                while (true)
                {
                    if (Server == null) return;
                    var service = ServerServiceList.FirstOrDefault(m => m.Server.Code == Server.Code);
                    if (service == null) return;
                    foreach (var item in service.CollectionServiceList)
                    {
                        UpdateCollectionStatus(item);
                    }
                    Thread.Sleep(60000);
                }
            });
            ListenerCollectionStatusThread.Start();
        }

        private void UpdateCollectionStatus(CollectReadService service)
        {
            if (service == null) return;
            try
            {
                lvCollection.Invoke(new MethodInvoker(delegate {
                    foreach (ListViewItem item in lvCollection.Items)
                    {
                        Collection collection = (Collection)item.Tag;
                        if (collection.Key == service.Collection.Key)
                        {
                            if (service.IsRead)
                            {
                                item.BackColor = Color.Green;
                            }
                            else
                            {
                                item.BackColor = Color.Red;
                            }
                            break;
                        }
                    }
                }));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
        #region Refresh Collection

        List<Refresh> Refreshes = new List<Refresh>();
        /// <summary>
        /// 开始刷新
        /// </summary>
        private void RefreshCollection()
        {
            try
            {
                var service = ServerServiceList.FirstOrDefault(m => m.Server.Code == Server.Code);
                for (int i = 0; i < lvAttributes.Items.Count; i++)
                {
                    Refresh refresh = new Refresh();
                    Collection collection = (Collection)lvAttributes.Items[i].Tag;
                    CollectReadService readService = service.CollectionServiceList.FirstOrDefault(m => m.Collection.Key == collection.Key);
                    refresh.RefreshCollectData(readService);
                    Refreshes.Add(refresh);
                    refresh.ValeuChanEvent += new EventHandler(UpdateCollectValue);
                }
            }
            catch (Exception ex)
            {

                LogHelper.Error("Mainform:" + ex.Message + "\r\n" + ex.StackTrace);
            }
        }
        /// <summary>
        /// 重新启动点位刷新
        /// </summary>
        private void RestartRefreshCollection()
        {
            StopRefreshCollection();
            RefreshCollection();
        }
        /// <summary>
        /// 停止刷新
        /// </summary>
        private void StopRefreshCollection()
        {
            foreach (var item in Refreshes)
            {
                item.Stop();
            }
            Refreshes.Clear();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private void UpdateCollectValue(object obj, EventArgs e)
        {
            Collection collection = (Collection)obj;
            lvAttributes.Invoke(new MethodInvoker(delegate {
                foreach (ListViewItem item in lvAttributes.Items)
                {
                    if (item.Text == collection.Name)
                    {
                        item.SubItems[2].Text = collection.Value.ToString();
                        break;
                    }
                }
            }));
        }

        class Refresh
        {
            private event EventHandler m_ValeuChanEvent;
            public event EventHandler ValeuChanEvent { add { m_ValeuChanEvent += value; } remove { m_ValeuChanEvent -= value; } }
            private Thread collectThead;
            public void RefreshCollectData(CollectReadService readService)
            {
                if (readService == null) return;
                collectThead = new Thread(() => {
                    while (true)
                    {
                        if (m_ValeuChanEvent != null)
                        {
                            m_ValeuChanEvent(readService.Collection, new EventArgs());
                        }
                        Thread.Sleep(readService.Collection.Frequency);
                    }
                });
                collectThead.Start();
            }

            public void Stop()
            {
                if (collectThead != null) collectThead.Abort();
            }
        }
        #endregion

        private void btCopy_Click(object sender, EventArgs e)
        {
            Form_CopyServer copyServer = new Form_CopyServer();
            copyServer.Server = Server;
            copyServer.Config();
            copyServer.ShowDialog(this);
            if (!copyServer.Status) return;
            UpdateServer(copyServer.Server);
            UpdateButton(lbCode.Text, Server?.Name);
        }
    }
}
